package com.wo.cloud.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wo.cloud.admin.dto.RolePermissionDto;
import com.wo.cloud.admin.entity.SysRolePermission;
import com.wo.cloud.admin.mapper.SysMenuMapper;
import com.wo.cloud.admin.mapper.SysRolePermissionMapper;
import com.wo.cloud.admin.service.IRolePermissionService;
import com.wo.cloud.core.entity.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/5/15 22:45
 * Description:
 */

@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements IRolePermissionService {

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRolePermissionMapper rolePermissionMapper;

    @Override
    public Response saveRolePermission(RolePermissionDto rolePermissionDto) {
        // 1. 获取该角色下所有权限
        String roleId = rolePermissionDto.getRoleId();
        List<String> sysMenuIds = rolePermissionMapper.selectList(new LambdaQueryWrapper<SysRolePermission>()
                .eq(SysRolePermission::getRoleId, roleId)).stream().map(SysRolePermission::getMenuId).collect(Collectors.toList());

        List<String> menuIds = rolePermissionDto.getMenuIds();

        if (ObjectUtil.isNotNull(sysMenuIds)) {
            // 2. 两个集合取差集
            List<String> deleteIds = (List<String>) CollectionUtils.subtract(sysMenuIds, menuIds);

            // 新增数据
            List<String> insertIds = (List<String>) CollectionUtils.subtract(menuIds, sysMenuIds);

            // 删除所有旧数据
            if (deleteIds.size() != 0) {
                rolePermissionMapper.delete(new LambdaQueryWrapper<SysRolePermission>().in(SysRolePermission::getMenuId, deleteIds));
            }

            // 3. 保存新增权限
            for (String menuId : insertIds) {
                SysRolePermission rolePermission = new SysRolePermission();
                rolePermission.setMenuId(menuId);
                rolePermission.setRoleId(roleId);
                rolePermissionMapper.insert(rolePermission);
            }
        }
        return Response.success();
    }
}
